package com.fly.locks.distributed.database;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 数据库Update锁
 * 
 * @author 00fly
 *
 */
public class DataUpdateLock
{
    private String key;
    
    private JdbcTemplate jdbcTemplate;
    
    public DataUpdateLock(String key, JdbcTemplate jdbcTemplate)
    {
        super();
        this.key = key;
        this.jdbcTemplate = jdbcTemplate;
        init();
    }
    
    /**
     * 初始化
     */
    private void init()
    {
        jdbcTemplate.update("DELETE FROM t_schedule_lock WHERE key_name=?", key);
        jdbcTemplate.update("INSERT INTO t_schedule_lock(key_name, time) VALUES(?, now())", key);
    }
    
    /**
     * 获取lock,并更新time为下次执行时间 now()+ seconds<BR>
     * 
     * 注意: 为了保证jdbcTemplate.update执行成功，一般设置seconds稍小于@Scheduled设置的运行间隔秒数
     * 
     * @return
     */
    public boolean getLock(long seconds)
    {
        return jdbcTemplate.update("UPDATE t_schedule_lock SET time = adddate(now(), INTERVAL ? SECOND) WHERE key_name = ? AND now() > time", seconds, key) > 0;
    }
}
